<template>
  <view class="reset-password-container">
    <!-- 导航栏 -->
    <u-navbar :title="useT('重置密码')" left-icon="arrow-left" leftIconColor="#ffffff" leftIconSize="40rpx" bg-color="transparent" :border="false" title-style="color: #ffffff;font-weight: bold;" @leftClick="goBack" />

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 白色卡片 -->
      <view class="reset-card">
        <!-- 头部区域 -->
        <view class="header">
          <view class="title-section">
            <text class="title">{{ useT('重置密码') }}</text>
            <text class="subtitle">{{ useT('请输入邮箱和新密码') }}</text>
          </view>
        </view>

        <!-- 输入区域 -->
        <view class="input-section">
          <!-- 邮箱输入框 -->
          <view class="input-group">
            <view class="input-wrapper">
              <view class="input-icon">
                <image class="icon-phone" src="/static/login/User.png" mode="aspectFit" />
              </view>
              <input class="input-field" type="text" :placeholder="useT('请输入邮箱')" v-model="email" />
            </view>
          </view>

          <!-- 验证码输入框 -->
          <view class="input-group">
            <view class="input-wrapper">
              <view class="input-icon">
                <image class="icon-shield" src="/static/login/code.png" mode="aspectFit" />
              </view>
              <input class="input-field" type="number" :placeholder="useT('请输入验证码')" v-model="verificationCode" maxlength="6" />
              <u-button class="get-code-btn" @click="getVerificationCode" :disabled="countdown > 0" size="mini" type="primary" :plain="countdown > 0">
                {{ countdown > 0 ? countdown + 's' : useT('获取验证码') }}
              </u-button>
            </view>
          </view>

          <!-- 新密码输入框 -->
          <view class="input-group">
            <view class="input-wrapper">
              <view class="input-icon">
                <image class="icon-shield" src="/static/login/code.png" mode="aspectFit" />
              </view>
              <input class="input-field" :type="showPassword ? 'text' : 'password'" :placeholder="useT('请输入新密码')" v-model="newPassword" />
              <view class="password-toggle" @click="togglePassword">
                <u-icon :name="showPassword ? 'eye-fill' : 'eye-off'" size="20" color="#999999"></u-icon>
              </view>
            </view>
          </view>

          <!-- 确认密码输入框 -->
          <view class="input-group">
            <view class="input-wrapper">
              <view class="input-icon">
                <image class="icon-shield" src="/static/login/code.png" mode="aspectFit" />
              </view>
              <input class="input-field" :type="showConfirmPassword ? 'text' : 'password'" :placeholder="useT('请确认新密码')" v-model="confirmPassword" />
              <view class="password-toggle" @click="toggleConfirmPassword">
                <u-icon :name="showConfirmPassword ? 'eye-fill' : 'eye-off'" size="20" color="#999999"></u-icon>
              </view>
            </view>
          </view>
        </view>

        <!-- 重置按钮 -->
        <view class="reset-btn-wrapper">
          <up-button
            type="primary"
            :text="useT('重置密码')"
            :custom-style="{
              width: '100%',
              height: '88rpx',
              borderRadius: '12rpx',
              fontSize: '32rpx',
              fontWeight: '500'
            }"
            @click="handleResetPassword"
          />
        </view>

        <!-- 密码强度提示 -->
        <view class="password-tips" v-if="newPassword">
          <view class="strength-bar">
            <view class="strength-item" :class="{ active: passwordStrength >= 1 }"></view>
            <view class="strength-item" :class="{ active: passwordStrength >= 2 }"></view>
            <view class="strength-item" :class="{ active: passwordStrength >= 3 }"></view>
            <view class="strength-item" :class="{ active: passwordStrength >= 4 }"></view>
          </view>
          <text class="strength-text">{{ passwordStrengthText }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { sendSmsCode, SMS_EVENTS, validatePassword } from '@/api/login.js';
import { resetPassword } from '@/api/user.js';
import { useT } from '@/utils/i18n.js';
import { computed, onUnmounted, ref } from 'vue';

// 响应式数据
const email = ref('');
const verificationCode = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const countdown = ref(0);
const timer = ref(null);

// 计算属性
const passwordStrength = computed(() => {
  if (!newPassword.value) return 0;
  let strength = 0;
  if (/[a-z]/.test(newPassword.value)) strength++;
  if (/[A-Z]/.test(newPassword.value)) strength++;
  if (/[0-9]/.test(newPassword.value)) strength++;
  if (/[^a-zA-Z0-9]/.test(newPassword.value)) strength++;
  return strength;
});

const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value;
  if (strength === 0) return '';
  if (strength < 2) return useT('密码强度较弱');
  if (strength < 3) return useT('密码强度中等');
  return useT('密码强度较强');
});

// 方法
// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 邮箱验证函数
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 获取验证码
const getVerificationCode = async () => {
  if (countdown.value > 0) return;

  // 验证邮箱格式
  if (!validateEmail(email.value)) {
    uni.showToast({
      title: useT('请输入正确的邮箱'),
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: useT('发送中.')
    });

    // 调用发送验证码API（接口字段名保持不变）
    const result = await sendSmsCode({
      phone: email.value, // 字段名保持phone，但传邮箱值
      type: SMS_EVENTS.RESET
    });

    uni.hideLoading();

    if (result.status === 200) {
      // 开始倒计时
      countdown.value = 60;
      timer.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer.value);
          timer.value = null;
        }
      }, 1000);

      uni.showToast({
        title: useT('验证码已发送'),
        icon: 'success'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error || useT('发送失败，请重试'),
      icon: 'none'
    });
  }
};

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

// 切换确认密码显示
const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

// 处理重置密码
const handleResetPassword = () => {
  // 验证邮箱格式
  if (!validateEmail(email.value)) {
    uni.showToast({
      title: useT('请输入正确的邮箱'),
      icon: 'none'
    });
    return;
  }

  // 验证验证码
  if (verificationCode.value.length !== 6) {
    uni.showToast({
      title: useT('请输入6位验证码'),
      icon: 'none'
    });
    return;
  }

  // 验证密码
  const passwordValidation = validatePassword(newPassword.value);
  if (!passwordValidation.isValid) {
    uni.showToast({
      title: passwordValidation.message,
      icon: 'none'
    });
    return;
  }

  // 验证确认密码
  if (newPassword.value !== confirmPassword.value) {
    uni.showToast({
      title: useT('两次输入的密码不一致！'),
      icon: 'none'
    });
    return;
  }

  // 执行重置密码
  performResetPassword();
};

// 执行重置密码
const performResetPassword = async () => {
  uni.showLoading({
    title: useT('重置中.')
  });

  try {
    const result = await resetPassword({
      account: email.value, // 字段名保持account，但传邮箱值
      password: newPassword.value,
      captcha: verificationCode.value
    });

    uni.hideLoading();

    if (result.status === 200) {
      uni.showToast({
        title: useT('密码重置成功'),
        icon: 'success'
      });

      // 重置成功后跳转到登录页面
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error || useT('重置失败，请重试'),
      icon: 'none'
    });
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style lang="scss" scoped>
.reset-password-container {
  min-height: 100vh;
  background: linear-gradient(to bottom, #4a90e2 20%, #ffffff 50%);
  position: relative;
}

.main-content {
  padding: 40rpx 40rpx;
  min-height: calc(100vh - 88rpx);
  padding-top: calc(70px + 44px + var(--status-bar-height));
  box-sizing: border-box;
}

.reset-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 60rpx 40rpx;
}

.header {
  margin-bottom: 60rpx;
}

.title-section {
  text-align: center;
}

.title {
  font-size: 48rpx;
  line-height: 50rpx;
  font-weight: bold;
  color: #000000;
  display: block;
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  line-height: 30rpx;
  color: #999999;
  display: block;
}

.input-section {
  margin-bottom: 60rpx;
}

.input-group {
  margin-bottom: 32rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  height: 88rpx;
  position: relative;
}

.input-icon {
  margin-right: 16rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .icon-phone {
    width: 38rpx;
    height: 38rpx;
  }

  .icon-shield {
    width: 38rpx;
    height: 38rpx;
  }
}

.input-field {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #333333;
  background: transparent;
  border: none;
  outline: none;
}

.input-field::placeholder {
  color: #999999;
}

.get-code-btn {
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  max-width: 160rpx;
}

.password-toggle {
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  cursor: pointer;
}

.reset-btn-wrapper {
  margin-bottom: 40rpx;
}

.password-tips {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.strength-bar {
  display: flex;
  margin-right: 20rpx;
}

.strength-item {
  width: 20rpx;
  height: 8rpx;
  background: #e0e0e0;
  margin-right: 8rpx;
  border-radius: 4rpx;
  transition: all 0.3s ease;

  &.active {
    background: #4a90e2;
  }
}

.strength-text {
  font-size: 24rpx;
  color: #666666;
}
</style>
